package com.zjc.netty.client.handler;

import com.zjc.netty.client.CustomChannelPool;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class ClientHandler extends ChannelDuplexHandler {
    private CustomChannelPool customChannelPool;

    public ClientHandler(CustomChannelPool customChannelPool) {
        this.customChannelPool = customChannelPool;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {

        if (customChannelPool != null) {
            customChannelPool.closeChannel(ctx.channel());
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        if (customChannelPool != null) {
            customChannelPool.addNew(ctx.channel());
        }
        ctx.writeAndFlush("hello netty");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        String receive = (String) msg;
        System.out.println(receive);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE && customChannelPool.canClose()) {
                //关闭连接
                ctx.channel().close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }

    }
}
